package com.netty.quartz.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.netty.common.annotation.DataSource;
import com.netty.common.enums.DataSourceType;
import com.netty.quartz.entity.SysJob;
import com.netty.quartz.mapper.SysJobMapper;
import com.netty.quartz.util.ScheduleUtils;
import com.netty.quartz.service.ISysJobService;

import org.quartz.Scheduler;
import org.quartz.SchedulerException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * 定时任务调度日志信息 服务层
 */
@Service
@DataSource(DataSourceType.SLAVE)
public class SysJobServiceImpl extends ServiceImpl<SysJobMapper, SysJob> implements ISysJobService {
    @Autowired
    private SysJobMapper sysJobMapper;

    @Autowired
    private Scheduler scheduler;
    @Override
    public List<SysJob> getJobList(Page<SysJob> page) {
        Page<SysJob> sysJobPage = sysJobMapper.selectPage(page, null);
        return sysJobPage.getRecords();
    }

    /**
     * 添加定时任务
     * @param sysJob
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int addJob(SysJob sysJob) {
        //设置默认状态为暂停 即创建定时任务的时候不立即执行
       // sysJob.setStatus(ScheduleConstants.Status.PAUSE.getValue());
        int rows = sysJobMapper.insert(sysJob);
        if (rows > 0) {
            try {
                ScheduleUtils.createScheduleJob(scheduler, sysJob);
            } catch (SchedulerException e) {
                throw new RuntimeException(e.getMessage());
            }
        }
        return rows;
    }

    @Override
    public SysJob getOneByCondition(QueryWrapper<SysJob> wrapper) {
      return this.getOne(wrapper);
    }
}
